#!/usr/bin/env bash

set -e

#节点环境
ENV="test"
#程序目录
INSTALL_DIR=/opt/gateway

#卫星服务
GW_CENTER_SERVER="estore.guanjieai.com:10000"
GW_API_KEY="15gDMT9uMinAFi5x1sVpWaftLV8UYJp8t8cLG1r8HHQUbMiJBjxNsZnMfzWvErLAQ6ym53K4C6A22iKUm"
GW_RP_URL="http://gongantest.guanjieai.com/airisk-tms/dcs/v1/sendHttpUrl"
GW_RP_KEY="1c43j9uych1p4sqqi2d2f9vngjgnivnx"
GW_RP_CID="39"
GW_PORT="7659"


#停止旧的服务
stopService() {
  systemctl stop gateway
}

startService() {
  systemctl start gateway
}


#节点配置setup
nodeSetup() {
  nodeBin="${INSTALL_DIR}/gateway"
  if [ ! -f "${nodeBin}" ]; then
    echo "gateway 程序不存在"
    exit 1
  fi
  cmd="${nodeBin} setup --defaults=${ENV} --config=${INSTALL_DIR}/config.yaml \
    --euplink.center-url=${GW_CENTER_SERVER} \
    --euplink.api-key=${GW_API_KEY} \
    --api.port=${GW_PORT} \
    --report.api-url=${GW_RP_URL} \
    --report.api-key=${GW_RP_KEY} \
    --report.company-id=${GW_RP_CID}  "
  echo -e "\n${cmd} => $?\n"
  $cmd
  #echo "配置文件 " ${DATA_DIR}/config.yaml
}


updateServiceFile() {
  cd $INSTALL_DIR
  ServerName="${1}.service"
  sed -i "s#HOME#${INSTALL_DIR}#g;s#LOG_FILE#${INSTALL_DIR}/gateway.log#g;s#ENV#${ENV}#g" ${ServerName}
  cd -
}

installService() {
  # 安装服务
  cd $INSTALL_DIR
  echo "install " ${1}
  ServerName=${1}.service
  updateServiceFile "${1}"
  rm -f /etc/systemd/system/${ServerName}
  ln -s ${INSTALL_DIR}/${ServerName} /etc/systemd/system/${ServerName}
  systemctl daemon-reload
  systemctl enable $1
}

#安装
install() {
  # 获取安装版本号
  if [ ! -f  ${INSTALL_DIR}/gateway ]; then
    echo "ERROR :  gateway程序不存在 "
    exit 1
  fi
  if [ ! -f  ${INSTALL_DIR}/gateway.service ]; then
    echo "ERROR :  gateway.service不存在 "
    exit 1
  fi
  echo "开始安装[gateway]"
  #停止旧服务
  set +e
  stopService
  set -e
  #初始化gateway
  nodeSetup
  installService "gateway"
  echo "install ok"
  #启动服务
  startService
  echo "start gateway ok"
}

main() {
  #解析参数
  set -- $(getopt -o e: -l env: -n ${0} -u -- "$@")
  while true; do
    case "${1}" in
    -e | --env)
      ENV="${2}"
      shift
      ;;
    --)
      shift
      break
      ;;
    *)
      echo "${1} is not option"
      ;;
    esac
    shift
  done

  #生产环境
  echo "ENV: ${ENV}"
  #echo "CENTER_SERVER: ${CENTER_SERVER}"

  install
}

main $@



